import { AGConnectCloudDB, CloudDBZoneConfig, CloudDBZone } from '@hw-agconnect/database'
import agconnect from '@hw-agconnect/api'
import '@hw-agconnect/cloudstorage'
import '@hw-agconnect/instance'
import type { StorageReference } from '@hw-agconnect/cloudstorage/dist/src/storagereference'
import ObjectType from '@/AGC/config/ObjectType.json'

let agcCloudDB: AGConnectCloudDB
let cloudDBZone: CloudDBZone
let reference: StorageReference

/**
 * 连接云数据库-初始化
 */
const initCloudDB = async () => {
  // 取对应数据处理位置的AGConnectCloudDB实例
  agcCloudDB = AGConnectCloudDB.getInstance()
  // 创建用户对象类型
  agcCloudDB.createObjectType(ObjectType)
  // 打开存储区
  await openCloudDBZone()
}

/**
 * 打开存储区
 */
const openCloudDBZone = async () => {
  // 打开存储区
  const cloudDBZoneConfig = new CloudDBZoneConfig('HealthwayCustom')
  cloudDBZone = await agcCloudDB.openCloudDBZone(cloudDBZoneConfig)
}

/**
 * 关闭云数据库
 */
export const closeCloudDBZone = () => {
  if (cloudDBZone && agcCloudDB) {
    agcCloudDB.closeCloudDBZone(cloudDBZone)
  }
}

/**
 * 连接云存储
 * @returns StorageReference
 */
const createStoragePerference = () => {
  // 初始化云存储实例
  const storageManagement = agconnect.cloudStorage()
  // 创建引用
  reference = storageManagement.storageReference()
}

export { initCloudDB, openCloudDBZone, agcCloudDB, cloudDBZone, createStoragePerference, reference }
